﻿using BepInEx;
using BepInEx.Configuration;
using Config;
using HarmonyLib;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

namespace HappyStudent.CfgMain
{
    [BepInPlugin("CfgMain", "CfgMain", "0.0.4")]
    public partial class CfgMain : BaseUnityPlugin
    {

        private void Start()
        {
            Harmony.CreateAndPatchAll(typeof(CfgMain));
            UpdateCheck();
            ReadPath();
        }


        [HarmonyPrefix, HarmonyPatch(typeof(Main), "StartGame")]
        public static void LoadOtherCfg()
        {
            Type type = typeof(Cfg);
            var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
            ConcurrentDictionary<string, PropertyInfo> propertiesDic = new ConcurrentDictionary<string, PropertyInfo>();
            foreach (var property in properties)
            {
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
                {
                    Type valueType = property.PropertyType.GetGenericArguments()[1];
                    propertiesDic.TryAdd(valueType.Name, property);
                }
            }
           
            if (IsUpdated)
            {
                Debug.LogWarning("====================================================");
                Debug.LogWarning("==Game update, start exporting game configurations==");
                Debug.LogWarning("====================================================");
                CfgExport.CfgExport.OutCfg(OutPath, propertiesDic);
                Debug.LogWarning("====================================================");
                Debug.LogWarning("====Exporting the game configuration is complete====");
                Debug.LogWarning("====================================================");
            }
            Debug.LogWarning("====================================================");
            Debug.LogWarning("==========Start loading mod configurations==========");
            Debug.LogWarning("====================================================");
            CfgLoad.CfgLoad.LoadCfg(LoadPath, propertiesDic);
            Debug.LogWarning("====================================================");
            Debug.LogWarning("==============Mod configuration loaded==============");
            Debug.LogWarning("====================================================");

        }
    }
}
